package com.xiguanlezz.cn.common.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/19 21:29
 * @Description：用于创建GRPC请求线程池的线程工厂
 */
public class ThreadFactoryBuilder {
    private boolean daemon;

    private String namePrefix;

    private AtomicInteger threadNumber = new AtomicInteger(1);

    public static ThreadFactoryBuilder newBuilder() {
        return new ThreadFactoryBuilder();
    }

    public ThreadFactoryBuilder daemon(boolean daemon) {
        this.daemon = daemon;
        return this;
    }

    public ThreadFactoryBuilder namePrefix(String namePrefix) {
        this.namePrefix = namePrefix;
        return this;
    }

    public ThreadFactory build() {
        // 使用JDK默认的线程工厂创建线程，后置设置线程属性
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        return new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = threadFactory.newThread(r);
                thread.setDaemon(ThreadFactoryBuilder.this.daemon);
                thread.setName(String.format("%s-%d", ThreadFactoryBuilder.this.namePrefix, threadNumber.getAndIncrement()));
                return thread;
            }
        };
    }

}

